﻿using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;
using ZGLXM.Domain;
using ZGLXM.Infra.Interface;

namespace ZGLXM.Infra.Repository
{
    public class RoleRepository : BaseRepository<Role>, IRoleRepository
    {
        private readonly BaseDataContext baseDataContext1;
        private readonly ILogger<BaseRepository<Role>> logger1;
        public RoleRepository(BaseDataContext baseDataContext, ILogger<BaseRepository<Role>> logger) : base(baseDataContext, logger)
        {
            baseDataContext1 = baseDataContext;
            logger1 = logger;
        }

        /// <summary>
        /// 事务添加角色权限信息
        /// </summary>
        /// <param name="role"></param>
        /// <param name="professionids"></param>
        /// <returns></returns>
        public async Task<bool> RoleProfessionInsert(Role role, int[] professionids)
        {
            try
            {
                var res = false;
                var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled);
                try
                {
                    //新增角色
                    var roleid = await baseDataContext1.Roles.AddAsync(role);
                    await baseDataContext1.SaveChangesAsync();
                    //新增用户角色关联
                    foreach (var item in professionids)
                    {
                        await baseDataContext1.RoleProfessions.AddAsync(new RoleProfession
                        {
                            RoleId = roleid.Entity.RoleId,
                            ProfessionId = item
                        });
                    }
                    await baseDataContext1.SaveChangesAsync();
                    //提交事务
                    scope.Complete();
                    res = true;
                    return res;
                }
                finally
                {
                    //回滚事务
                    scope.Dispose();
                }
            }
            catch (Exception ex)
            {
                logger1.LogError("添加角色权限异常" + ex.Message); ;
                throw;
            }
        }
    }
}
